
package com.epam.video.test;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Slava
 */
public class Config {
  private static final String TEST_FILE_NAME = "test.json";

  private static final String IVC1_FILE_NAME = "ivc1.json";

  private static final String IVC2_FILE_NAME = "ivc2.json";

  private static final String SI1_FILE_NAME = "si1.json";

  private static final String SI2_FILE_NAME = "si2.json";

  private static Config sharedInstance;

  private JSONObject configRoot;

  private Context context;

  public static Config instance() {
    if (sharedInstance == null) {
      sharedInstance = new Config();
    }
    return sharedInstance;
  }

  private Config() {}

  public void setContext(final Context context) {
    this.context = context;
  }

  public String getIvc1Json() {
    return getConfigJsonRoot(IVC1_FILE_NAME).toString();
  }

  public String getIvc2Json() {
    return getConfigJsonRoot(IVC2_FILE_NAME).toString();
  }

  public String getSi1Json() {
    return getConfigJsonRoot(SI1_FILE_NAME).toString();
  }

  public String getSi2Json() {
    return getConfigJsonRoot(SI2_FILE_NAME).toString();
  }

  public String getListOfIvcsJson() {
    return getConfigJsonRoot(TEST_FILE_NAME).toString();
  }

  private String assetAsString(final String assetName) {
    try {
      InputStream stream = context.getResources().getAssets().open(assetName);
      final int size = stream.available();

      byte[] array = new byte[size];

      stream.read(array);

      return new String(array);
    } catch (IOException e) {
      return null;
    }
  }

  private JSONObject getConfigJsonRoot(final String fileName) {
    String str = assetAsString(fileName);
    try {
      configRoot = new JSONObject(str);
    } catch (JSONException e) {
      Log.e("Config", String.format("creating base config: %s", e.toString()));
    }
    return configRoot;
  }
}
